package com.module.home.ui.home.provider

import android.util.Base64
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.ServerHealthTypeDataModel
import com.common.app.data.bean.UpKvDataModel
import com.common.app.data.bean.home.HomeMainCardModel
import com.common.app.utls.BrotliCompressionEx
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.isEmpty
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils.getString
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusChartData
import com.module.ble.data.bean.SleepChartValueData
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.utils.groupSleepDataByQualityAndTime
import com.module.ble.widget.SleepStageChart
import com.module.home.R
import kotlin.random.Random


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/31
 *
 * 描述：睡眠AI信息卡片
 *
 * 修订历史：
 *
 */
class CloudReminderSleepProvider(override val itemViewType: Int = 1,
                                 override val layoutId: Int = R.layout.home_provider_cloud_reminder_sleep_item,
) : BaseItemProvider<HomeMainCardModel>(),OnClickListener {

    private val sleepData = mutableListOf<CusChartData>()
    var points = mutableListOf<String>()

    var commonMessageRelayModel: CommonMessageRelayModel? = null

    init {
        addChildClickViewIds(R.id.tvAiSuggestion)
    }

    override fun convert(helper: BaseViewHolder, item: HomeMainCardModel) {
        val sleepStageChart = helper.getView<SleepStageChart>(R.id.sleepStageChart)
        sleepStageChart.setTouchEnabled(false)
        // 设置数据
        sleepStageChart.setRowCount(4)
        sleepStageChart.setSleepStageData(sleepData)

        // 设置触摸监听
        sleepStageChart.setOnSleepStageTouchListener (object :
            SleepStageChart.OnSleepStageTouchListener{
            override fun onStageTouch(stageData: CusChartData, stageName: String) {
                // 处理触摸事件
                Log.d("SleepChart", "触摸了 $stageName，时长：${stageData.timeLong}分钟")
                ToastUtils.showToast("触摸了 $stageName，时长：${stageData.timeLong}分钟")
            }

            override fun onTouchReleased() {
            }

        })

        helper.setText(R.id.tvTopTitle,item.title)
        helper.setText(R.id.tvTopSummary,item.summary)

        helper.setGone(R.id.totalImprovement,(item.ai_analyze_result==null))

        item.ai_analyze_result?.let { resultIt->
            helper.setGone(R.id.tvImprovementHint, resultIt.improvement.isNullOrEmpty())
            helper.setGone(R.id.tvInfluenceHint, resultIt.impact.isNullOrEmpty())
            helper.setGone(R.id.tvReasonHint, resultIt.reason.isNullOrEmpty())
            helper.setGone(R.id.tvSuggestionHint, resultIt.suggestion.isNullOrEmpty())

            helper.setGone(R.id.tvImprovement, resultIt.improvement.isNullOrEmpty())
            helper.setGone(R.id.tvInfluence, resultIt.impact.isNullOrEmpty())
            helper.setGone(R.id.tvReason, resultIt.reason.isNullOrEmpty())
            helper.setGone(R.id.tvSuggestion, resultIt.suggestion.isNullOrEmpty())

            helper.setText(R.id.tvImprovement,resultIt.improvement)
            helper.setText(R.id.tvInfluence,resultIt.impact)
            helper.setText(R.id.tvReason,resultIt.reason)
            helper.setText(R.id.tvSuggestion,resultIt.suggestion)

            commonMessageRelayModel = CommonMessageRelayModel(webType = item.id, skipPath = item.possible_questions)
            helper.setGone(R.id.tvAiSuggestion, item.possible_questions.isNullOrEmpty())
            helper.setText(R.id.tvAiSuggestion,item.possible_questions)
            helper.setText(R.id.tvSleepTime2,"8${getString(R.string.common_hours_hint)}")
        }

        item.chart_data.isNullOrEmpty().no {
            try {
                // 先将Base64字符串解码回字节数组
                val decodedBytes = Base64.decode(item.chart_data, Base64.DEFAULT)
                // 然后解压缩
                BrotliCompressionEx.decompressToStringByObd(decodedBytes).let { dataStrIt ->
                    doOnIOThread {

                        // 根据数据类型进行不同的处理
                        var totalDuration = 0L//睡眠总时长，单位：分钟
                        val mKvDataList: List<UpKvDataModel> = JsonUtils.fromJsonList(dataStrIt)
                        val sleepDataList = arrayListOf<UserSleepInfo>()
                        mKvDataList.forEach { kvDataIt->
                            JsonUtils.fromJson(kvDataIt.value ?: "", UserSleepInfo::class.java)?.let { beanIt ->
                                beanIt.sysStat = 1
                                sleepDataList.add(beanIt)
                            }
                        }

                        sleepDataList.isNullOrEmpty().no {
                            val groupedSleepData = groupSleepDataByQualityAndTime(sleepDataList)
                            sleepData.addAll(groupedSleepData)
                            sleepData.forEach {sleepDataIt->
                                totalDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                            }
//                        points = TimeUtils.calculateTimeBreakpoints(sleepData[0].createdTime, sleepData.last().createdTime, outFormat = "%02d:%02d") as MutableList<String>
                            points = TimeUtils.calculateTimeBreakpointsRounded(
                                sleepDataList.first().createdTime,
                                sleepDataList.last().createdTime
                            ) as MutableList<String>
                        }

                        
//                        val tempData: List<UserSleepInfo> = JsonUtils.fromJsonList(dataStrIt)
//                        var totalDuration = 0L//睡眠总时长，单位：分钟
//                        Log.e("CloudReminderSleepProvider", "dataList----decompressedJson: $dataStrIt")
//
//                        // 至少需要两条数据才能计算时长
//                        if (tempData.size > 1) {
//
//                            sleepData.clear()
//
//                            val listItStr = JsonUtils.toJson(tempData)
//                            val groupedSleepData = groupSleepDataByQualityAndTime(tempData)
//                            sleepData.addAll(groupedSleepData)
//                            sleepData.forEach {sleepDataIt->
//                                totalDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
//                            }
////                        points = TimeUtils.calculateTimeBreakpoints(sleepData[0].createdTime, sleepData.last().createdTime, outFormat = "%02d:%02d") as MutableList<String>
//                            points = TimeUtils.calculateTimeBreakpointsRounded(
//                                tempData.first().createdTime,
//                                tempData.last().createdTime
//                            ) as MutableList<String>
//                        }

                        doOnUiThread {
                            helper.setText(R.id.tvSleepTime,TimeUtils.formatTime((totalDuration*60*1000), showHour = true, showMin = true))
                            sleepStageChart.setSleepStageData(sleepData)
                            helper.setText(R.id.tvTimeOne,points[0])
                            helper.setText(R.id.tvTimeTwo,points[1])
                            helper.setText(R.id.tvTimeThree,points[2])
                            helper.setText(R.id.tvTimeFour,points[3])
                            helper.setText(R.id.tvTimeFive,points[4])
                        }
                    }
                }
            }catch (e: Exception){
                Log.e("CloudReminderSleepProvider", "数据解压缩任务执行失败: ${e.message}", e)
            }
        }

        helper.getView<TextView>(R.id.tvAiSuggestion).setOnClickListener(onClick = this)
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvAiSuggestion -> LiveEventBus.get(KeyEvents.KEY_HOME_SCENE_MODE_CONFIG).post(commonMessageRelayModel)
            else -> {
            }
        }
    }
}